package com.autotest.nore.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.autotest.nore.common.constants.ReportSourceType;
import com.autotest.nore.domain.*;
import com.autotest.nore.mapper.*;
import com.autotest.nore.dto.*;
import com.autotest.nore.request.CaseApiRequest;
import com.autotest.nore.request.CaseRequest;
import com.autotest.nore.response.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CaseJsonCreateService {

    @Value("${task.file.path}")
    public String TASK_FILE_PATH;

    private static final String DOWNLOAD_PATH = "/openapi/task/file/download";


    @Autowired
    private CaseMapper caseMapper;

    @Autowired
    private ApiMapper apiMapper;

    @Autowired
    private CaseApiMapper caseApiMapper;

    @Autowired
    private DebugDataMapper debugDataMapper;

    @Autowired
    private DomainMapper domainMapper;

    @Autowired
    private DatabaseMapper databaseMapper;

    public TestCaseApiResponse getApiTestCaseJson(String environmentId, String SourceType, TaskTestCaseResponse taskTestCase){
        // 拼装Api用例
        TestCaseApiResponse testCaseApi = new TestCaseApiResponse();
        if(SourceType.equals(ReportSourceType.TEMP.toString())){
            DebugData debugData = debugDataMapper.getDebugData(taskTestCase.getCaseId());
            CaseRequest caseRequest = JSONObject.parseObject(debugData.getData(), CaseRequest.class);
            testCaseApi.setComment(caseRequest.getDescription());
            testCaseApi.setCaseId(taskTestCase.getCaseId());
            testCaseApi.setCaseName(caseRequest.getName());
            // 组装自定义函数
            testCaseApi.setFunctions(this.getCaseFunctions(caseRequest.getCommonParam().getJSONArray("functions")));
            // 组装用例公参
            testCaseApi.setParams(this.getCaseParams(caseRequest.getCommonParam().getJSONArray("params")));
            List<CaseApiRequest> caseApis = caseRequest.getCaseApis();
            List<TestCaseApiDataResponse> apiList = new ArrayList<>();
            for (CaseApiRequest caseApiRequest:caseApis){
                TestCaseApiDataResponse apiData = new TestCaseApiDataResponse();
                ApiDTO apiDTO = apiMapper.getApiDetail(caseApiRequest.getApiId());
                apiData.setApiId(caseApiRequest.getApiId());
                apiData.setApiName(apiDTO.getName());
                apiData.setApiDesc(caseApiRequest.getDescription());
                apiData.setUrl(this.getUrlBySign(environmentId, apiDTO.getDomainSign(), apiDTO.getPath()));
                apiData.setPath(apiDTO.getPath());
                apiData.setMethod(apiDTO.getMethod());
                apiData.setProtocol(apiDTO.getProtocol());
                // 拼接header
                apiData.setHeaders(this.getApiHeader(caseRequest.getCommonParam().getString("header"), caseApiRequest.getHeader()));
                // 拼接proxy
//                apiData.setProxies(this.getApiProxy(caseRequest.getCommonParam().getString("proxy")));
                // 组装body
                apiData.setBody(caseApiRequest.getBody());
                // 组装query
                apiData.setQuery(this.getApiQuery(caseApiRequest.getQuery()));
                // 组装rest
                apiData.setRest(this.getApiRest(caseApiRequest.getRest()));
                // 组装relation assertion
                apiData.setRelations(caseApiRequest.getRelation());
                apiData.setAssertions(caseApiRequest.getAssertion());
                // 组装controller
                apiData.setController(this.getApiController(environmentId, caseApiRequest.getController()));
                apiList.add(apiData);
            }
            testCaseApi.setApiList(apiList);
        }else {
            CaseDTO caseDTO = caseMapper.getCaseDetail(taskTestCase.getCaseId());
            testCaseApi.setComment(caseDTO.getDescription());
            testCaseApi.setCaseId(taskTestCase.getCaseId());
            testCaseApi.setCaseName(caseDTO.getName());
            JSONObject commonParam = JSONObject.parseObject(caseDTO.getCommonParam());
            // 组装自定义函数
            testCaseApi.setFunctions(this.getCaseFunctions(commonParam.getJSONArray("functions")));
            // 组装用例公参
            testCaseApi.setParams(this.getCaseParams(commonParam.getJSONArray("params")));
            List<CaseApiDTO> caseApiDTOS = caseApiMapper.getCaseApiList(taskTestCase.getCaseId());
            List<TestCaseApiDataResponse> apiList = new ArrayList<>();
            for(CaseApiDTO caseApiDTO: caseApiDTOS){
                TestCaseApiDataResponse apiData = new TestCaseApiDataResponse();
                apiData.setApiId(caseApiDTO.getApiId());
                apiData.setApiName(caseApiDTO.getApiName());
                apiData.setApiDesc(caseApiDTO.getDescription());
                apiData.setUrl(this.getUrlBySign(environmentId, caseApiDTO.getApiDomainSign(), caseApiDTO.getApiPath()));
                apiData.setPath(caseApiDTO.getApiPath());
                apiData.setMethod(caseApiDTO.getApiMethod());
                apiData.setProtocol(caseApiDTO.getApiProtocol());
                // 拼接header
                JSONArray headers = JSONArray.parseArray(caseApiDTO.getHeader());
                apiData.setHeaders(this.getApiHeader(commonParam.getString("header"), headers));
                // 拼接proxy
//                apiData.setProxies(this.getApiProxy(commonParam.getString("proxy")));
                // 组装body
                apiData.setBody(JSONObject.parseObject(caseApiDTO.getBody()));
                // 组装query
                apiData.setQuery(this.getApiQuery(JSONArray.parseArray(caseApiDTO.getQuery())));
                // 组装rest
                apiData.setRest(this.getApiRest(JSONArray.parseArray(caseApiDTO.getRest())));
                // 组装relation assertion
                apiData.setRelations(JSONArray.parseArray(caseApiDTO.getRelation()));
                apiData.setAssertions(JSONArray.parseArray(caseApiDTO.getAssertion()));
                // 组装controller
                apiData.setController(this.getApiController(environmentId, JSONArray.parseArray(caseApiDTO.getController())));
                apiList.add(apiData);
            }
            testCaseApi.setApiList(apiList);
        }

        return testCaseApi;
    }

    public JSONObject getApiController(String environmentId, JSONArray controller){
        JSONObject controllerObj = new JSONObject();
        if(controller == null){
            return controllerObj;
        }
        JSONArray pre = new JSONArray();    // 前置脚本和sql
        JSONArray post = new JSONArray();   // 后置脚本和sql
        for(int i =0; i<controller.size(); i++) {
            JSONObject controllerData = controller.getJSONObject(i);
            String controllerName = controllerData.getString("name");
            String controllerValue = controllerData.getString("value");
            if(controllerName.contains("Sql") && !controllerValue.equals("{}")){ // 处理sql中的数据库连接信息
                JSONObject value = JSONObject.parseObject(controllerValue);
                Database database = databaseMapper.getDatabaseByName(environmentId, value.getString("db"));
                JSONObject db = new JSONObject();
                if(database != null){
                    db = JSONObject.parseObject(database.getConnectInfo());
                    db.put("tpz", database.getDatabaseType());
                    db.put("db", database.getDatabaseKey());
                }
                value.put("db", db);
                controllerData.put("value", value.toJSONString());
            }
            if(controllerName.startsWith("pre")){
                pre.add(controllerData);
            }else if(controllerName.startsWith("post")){
                post.add(controllerData);
            }else {
                controllerObj.put(controllerName, controllerData.getString("value"));
            }
        }
        if(pre.size()>0){
            controllerObj.put("pre", pre);
        }
        if(post.size()>0){
            controllerObj.put("post", post);
        }
        return controllerObj;
    }

    public JSONObject getApiRest(JSONArray rest){
        JSONObject restObj = new JSONObject();
        if(rest == null){
            return restObj;
        }
        for(int i =0; i<rest.size(); i++) {
            JSONObject restData = rest.getJSONObject(i);
            restObj.put(restData.getString("name"), restData.getString("value"));
        }
        return restObj;
    }

    public JSONObject getApiQuery(JSONArray query){
        JSONObject queryObj = new JSONObject();
        if(query==null){
            return queryObj;
        }
        for(int i =0; i<query.size(); i++) {
            JSONObject queryData = query.getJSONObject(i);
            queryObj.put(queryData.getString("name"), queryData.getString("value"));
        }
        return queryObj;
    }



    public JSONObject getApiHeader(String headerId, JSONArray headerList){
        // 合并接口用例请求头
        try{
            JSONObject header = new JSONObject();
            if(headerList == null){
                return header;
            }
            for(int i =0; i<headerList.size(); i++){
                JSONObject paramObj = headerList.getJSONObject(i);
                String headerKey = paramObj.getString("name");
                String headerValue = paramObj.getString("value");
                for (String item : header.keySet()) {
                    // 用例中的同名header key 替换公参中的 key不区分大小写
                    if (item.equalsIgnoreCase(headerKey)) {
                        header.remove(item);
                        break;
                    }
                }
                header.put(headerKey, headerValue);
            }
            return header;
        }catch (Exception exception) {
            return new JSONObject();
        }
    }

    public JSONArray getCaseFunctions(JSONArray functions){
        // 获取用例所需要的自定义函数
        JSONArray functionList = new JSONArray();


        return functionList;
    }

    public JSONObject getCaseParams(JSONArray params){
        // 获取用例所需要的公参
        JSONObject paramObj = new JSONObject();
        for(int i=0; i<params.size();i++){
            String paramId = params.getString(i);
        }
        return paramObj;
    }

    public String getUrlBySign( String environmentId, String domainSign, String path){
        // 匹配环境下的域名 匹配不到则为null
        String url = null;
        if(domainSign != null && !domainSign.equals("")){
            Domain domain = domainMapper.getDomainByName(environmentId, domainSign);
            if(domain != null) {
                url = domain.getDomainData();
            }
        }else {
            List<Domain> domainList = domainMapper.getPathDomainList(environmentId);
            for(Domain domain: domainList){
                String domainKey = domain.getDomainKey();
                if(path.startsWith(domainKey)){
                    url = domain.getDomainData();
                    break;
                }
            }
        }
        return url;
    }

}
